﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Thor.Domain;

namespace Thor.SharePoint2007.WebServices
{
    public class SharePointCalendarProvider : CalendarProviderBase
    {
        public override AuthenticationResult Authenticate(NetworkCredential credential, string serviceUrl)
        {
            AuthenticationResult result = new AuthenticationResult();

            try
            {
                SharePoint.Lists.Lists svc = new Thor.SharePoint2007.WebServices.SharePoint.Lists.Lists();
                svc.Credentials = credential;
                svc.Url = serviceUrl;

                var lists = svc.GetListCollection();

                result.Success = true;
                result.Message = "Authenticated.";
            }
            catch(Exception ex)
            {
                result.Success = false;
                result.Message = ex.Message;
            }

            return result;
        }

        protected override Calendar OnGetCalendar(CalendarRequest request)
        {
            SharePoint.Lists.Lists svc = new Thor.SharePoint2007.WebServices.SharePoint.Lists.Lists();
            svc.Credentials = request.Credential;
            svc.Url = request.ServiceUrl;

            var query = SPCalendar.GetQueryNode(request);

            var response = svc.GetListItems(request.CalendarId, null, query, null, null, null, null);

            return SPCalendar.GetCalendar(response);
        }

        protected override AppointmentResponse OnBookDirect(AppointmentRequest appointmentRequest)
        {
            AppointmentResponse result = new AppointmentResponse();

            try
            {
                SharePoint.Lists.Lists svc = new Thor.SharePoint2007.WebServices.SharePoint.Lists.Lists();
                svc.Credentials = appointmentRequest.Credential;
                svc.Url = appointmentRequest.ServiceUrl;

                svc.UpdateListItems(appointmentRequest.CalendarId, SPEventRequest.GetEventRequest(appointmentRequest));
                
                result.Success = true;
                result.Message = "The appointment has been booked.";
            }
            catch (Exception ex)
            {
                result.Success = false;
                result.Message = ex.Message;
            }

            return result;
        }

        protected override AppointmentResponse OnBookViaAgent(AppointmentRequest appointmentRequest)
        {
            //In the case of SharePoint we currently do not have the book via
            //agent feature implemented. In the future this could be
            //implemented using a workflow.
            return OnBookDirect(appointmentRequest);
        }
    }
}
